var app = getApp();
var QQMapWX = require("../../qqmap-wx-jssdk.min.js")
var demo = new QQMapWX({
  key: 'UTFBZ-RBN3V-FNFPU-U4XES-2RK62-TDFPK' // 必填
});
const port = require('../../config.js');
const mainIndex = require('../index.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    cid: '',
    top: '',
    lastY: '',
    preHidden: 0,
    card: [],
    types: 0,
    bgImg: '',
    bgImgg: '',
    color: '#000',
    imgPath: port.imgPath,
    video: '',
    title: '',
    className: false,
    imgModel: 'aspectFill',
    limit: 1,
    tatol: 0,
    nonet: true,
    wetherLoadding: 'block',
    opacity: 1,
    showModal: false,
    plus_cardid: '',
    formid: '',
    apply_text: '',
    indexShuttle: mainIndex.indexShuttle,  //跳转分包shuttle统一路径
    indexMessage: mainIndex.indexMessage,  //跳转分包message统一路径
    indexCenter: mainIndex.indexCenter,  //跳转分包center统一路径
    showvideo: false, //是否显示真视频
    vlogo: false,   //合伙人logo
  },

  exchange: function(e){
    var that=this;
    //显示申请消息输入框
    this.setData({
      showModal: true
    })
    //设置被请求者cardid
    that.setData({
      plus_cardid: that.data.cid,
    })
  },
  showvideo: function () {
    var that = this;
    that.setData({
      showvideo: true,
    })
    var videoContext = wx.createVideoContext('myVideo');
    // videoContext.seek(0);
    videoContext.play();
  },
  videoPause: function () {
    var that = this;
    that.setData({
      showvideo: false,
    })
  },
  //判断长度
  chargeString: function(value){
    var value = value;
    var strLength = 0;
    for (var i = 0; i < value.length; i++) {
      var type = value.charCodeAt(i)
      if (type >= 19968 && type <= 40869) { //为中文字符
        strLength = strLength + 2;
      } else if (type >= 48 && type <= 57) {  //为数字字符
        strLength++;
      } else if (type >= 65 && type <= 122) {  //为英文字符
        strLength++;
      } else {  //其他字符
        strLength++;
      }
    }
    return strLength;
  },

  formsubmit: function (e) {
    var that = this
    // 设置表单信息
    var liuyan = that.chargeString(e.detail.value.addMsg);
    if (liuyan > 68){
      wx.showToast({
        title: '留言不可超过30个字哦~',
        icon: 'none',
        mask: true,
        duration: 1500
      })
      return
    }
    that.setData({
      formid: e.detail.formId,
      apply_text: e.detail.value.addMsg
    })
    //发送申请请求
    app.getUserInfo(function (personInfo) {
      var token = personInfo.token;
      var uid = personInfo.uid;
      var openid = personInfo.openId;
      //发送请求交换信息
      wx.request({
        url: port.CardApply,
        method: 'POST',
        data: {
          openid: openid,
          cardid: that.data.cid,
          plus_cardid: that.data.plus_cardid,
          formid: that.data.formid,
          apply_text: that.data.apply_text,
        },
        header: {
          //data为'pageSize=1&pageNum=10'类时，设置参数内容类型为x-www-form-urlencoded
          'content-type': 'application/json',
          "Authorization": "Bearer " + token
        },
        success: function (res) {
          that.setData({
            showModal: false
          });
          wx.showToast({
            title: res.data.message,
          })
        }
      })
    })
  },
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },

  // viewH5: function(){
  //   var that = this;
  //   var id_h5Bg = that.data.card.templet_sz.id_h5bg;
  //   var path;
  //   if (id_h5Bg == 1) {
  //     path = '/pages/animateCard/animateCard?cid=' + this.data.card.id + '&binding=' + 1
  //   } else if (id_h5Bg == 2) {
  //     path = '/pages/animateCard/animateCardSecond?cid=' + this.data.card.id + '&binding=' + 1
  //   } else if (id_h5Bg == 3) {
  //     path = '/pages/animateCard/animateThird?cid=' + this.data.card.id + '&binding=' + 1
  //   } else if (id_h5Bg == "") {
  //     path = '/pages/animateCard/animateThird?cid=' + this.data.card.id + '&binding=' + 1
  //   }
  //   wx.navigateTo({
  //     url: path,
  //   })
  // },

  // goH5: function () {
  //   wx.navigateTo({
  //     url: '../H5select/H5select',
  //   })
  // },

  //個人信息
  permessage: function () {
    var that = this;
    var cid = that.data.card.id;
    var indexMessage = that.data.indexMessage;
    if (!cid) {
      wx.showToast({
        icon: 'success',
        image: '/images/error.png',
        title: '请先添加名片',
      })
    } else {
      wx.navigateTo({
        url: indexMessage + '/permessage/permessage?cid=' + cid,
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    var that = this
    //获取全局数据
    var globalData = app.globalData;
    if (!globalData.isConnected) {
      that.setData({
        nonet: false
      })
      wx.hideLoading()
      wx.showModal({
        showCancel: false,
        content: '网络连接出错！',
        confirmText: '我知道了',
      })
    }
    //获取设备信息
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          top: res.windowHeight
        });
      }
    });
    //判断是否为自己的名片
    var my = options.my ? options.my : 0;
    if (my == 0) {
      that.setData({
        preHidden: 1
      })
    }
    if(options.binding){
      wx.showToast({
        title: '已为你存入咖片夹,快去查看吧~',
        icon: 'none',
        duration: 3000
      })
    }
    //获取预览的名片cid
    var binding = options.binding ? options.binding : 0;
    var cid = options.cid;
    that.setData({
      cid: cid
    })
    app.getUserInfo(function (personInfo) {
      var token = personInfo.token;
      var uid = personInfo.uid;
      wx.request({
        url: port.CardLook,//请求地址
        header: {//请求头
          "Content-Type": "applciation/json",
          "Authorization": "Bearer " + token
        },
        data: { 'cid': cid, 'uid': uid, 'binding': binding },
        method: "post",//get为默认方法/POST
        success: function (res) {
          //加载中Logo展示
          var opacity = 1;
          var timer = setInterval(function () {
            opacity = opacity - 0.25;
            that.setData({
              opacity: opacity,
            })
            if (opacity < 0.5) {
              that.setData({
                wetherLoadding: 'none'
              })
            }
          }, 200)

          if (res.data.status == 'success') {
            if (res.data.data.status == 1 && uid != res.data.data.uid) {
              wx.showModal({
                title: '提示',
                content: '此名片已被禁用,无法查看 点击确定返回',
                showCancel: false,
                success: function (red) {
                  if (red.confirm) {
                    wx.navigateBack({
                      delta: 1
                    })
                  }
                }
              })
            } else {
              if (res.data.data.video != '' && res.data.data.video != null) {
                setTimeout(function () {
                  var video = JSON.parse(res.data.data.video);
                  that.setData({
                    title: video.title,
                    video: video.video,
                  })
                }, 1000)
              }
              var bigBackground;
              if (res.data.data.templet_sz.bigBg != '' && res.data.data.templet_sz.bigBg != null) {
                bigBackground = res.data.data.templet_sz.bigBg
              } else {
                bigBackground = port.imgPath + "/new-background/newbg-2long.png";
              }
              if (res.data.data.album[0] == null) {
                var user_imgsName = "相册"
                that.setData({
                  card: res.data.data,
                  types: res.data.data.type,
                  user_imgs: res.data.data.album,
                  user_imgsName: user_imgsName,
                  bgImg: bigBackground,
                  adress: res.data.data.ssq + res.data.data.address,
                  tatol: res.data.tatol
                })
              } else {
                that.setData({
                  card: res.data.data,
                  types: res.data.data.type,
                  user_imgs: res.data.data.album,
                  user_imgsName: res.data.data.album[0].name,
                  bgImg: bigBackground,
                  adress: res.data.data.ssq + res.data.data.address,
                  tatol: res.data.tatol
                })
              }

            }
          } else {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              mask: true,
              duration: 2000,
              success: function () {
                setTimeout(function () {
                  wx.navigateBack({
                    delta: 1
                  })
                }, 2000)
              }
            })
          }
        },
        fail: function (err) { },//请求失败
        complete: function (suc) {//请求完成后执行的函数
        }
      })
      //判断是否存在名片
      wx.request({
        url: port.CardMy,//请求地址
        header: {//请求头
          "Content-Type": "applciation/json",
          "Authorization": "Bearer " + token
        },
        data: { 'uid': uid },
        method: "post",//get为默认方法/POST
        success: function (res) {
          if (res.data.status == 'success') {
          } else {
            that.setData({
              preHidden: 2
            })
            wx.hideLoading()
          }
        },
        fail: function (err) {
          wx.hideLoading()
        },//请求失败
        complete: function (suc) {//请求完成后执行的函数
        }
      })
    })
  },
  //跳转到咖片夹
  cartCollect: function(){
    var that = this;
    wx.switchTab({
      url: 'cardHolder',
    })
  },
  //跳转创建名片
  createCard: function(){
    var that = this;
    var indexMessage = that.data.indexMessage;
    wx.navigateTo({
      url: indexMessage + '/newpermessage/newpermessage',
    })
  },
  lookCard:function(){
    wx.switchTab({
      url: '/pages/index/library',
    })
  },

  eaditCard: function () {
    var that = this;
    var cid = that.data.card.id;
    var typ = that.data.types;
    app.getUserInfo(function (personInfo) {
      var token = personInfo.token;
      var uid = personInfo.uid;
      wx.request({
        url: port.CardCollect,//请求地址
        header: {//请求头
          "Content-Type": "applciation/json",
          "Authorization": "Bearer " + token
        },
        data: { 'cid': cid, 'uid': uid, 'type': typ },
        method: "post",//get为默认方法/POST
        success: function (res) {
          if (res.data.status == 'success') {
            that.setData({
              types: res.data.data
            })
          } else {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              mask: true,
              duration: 2000,
            })
          }
        },
        fail: function (err) { },//请求失败
        complete: function (suc) {//请求完成后执行的函数

        }
      })
    })
  },
  //拨打电话
  callPhone: function () {
    var that = this
    wx.makePhoneCall({
      phoneNumber: that.data.card.mobile //仅为示例，并非真实的电话号码
    })
  },
  toMain: function () {
    var that = this;
    wx.switchTab({
      url: 'myCard',
    })
  },
  //保存手机号
  downPhone: function () {
    var that = this
    wx.addPhoneContact({
      firstName: that.data.card.username,//联系人姓名  
      mobilePhoneNumber: that.data.card.mobile,//联系人手机号  
    })
  },
  // 点击出现地图
  goMap: function () {
    var that = this

    demo.geocoder({
      address: that.data.adress,
      success: res => {

        var lat = res.result.location.lat;
        var lng = res.result.location.lng
        wx.getLocation({
          type: 'gcj02', //返回可以用于wx.openLocation的经纬度
          success: function (res) {
            wx.openLocation({
              latitude: lat,
              longitude: lng,
              scale: 28,
              name: that.data.adress
            })
          }
        })
      },
      fail: function (res) {
      },
      complete: function (res) {
      }
    });
  },
  //变换图片排列
  change: function () {
    var that = this;
    that.setData({
      className: true,
      imgModel: 'widthFix'
    })
  },
  changeImg: function () {
    var that = this;
    that.setData({
      className: false,
      imgModel: 'aspectFill'
    })
  },
  //图片点击放大
  imgYu: function (e) {
    var that = this;
    var imgs = that.data.user_imgs[0].image
    var arr = [];
    for (var i = 0; i < imgs.length; i++) {
      var list = that.data.imgPath + imgs[i]
      arr.push(list)
    }
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: arr, // 需要预览的图片http链接列表
    })
  },
  // 头像放大
  headerImg: function () {
    var that = this;
    var imgs = that.data.card.avatar
    wx.previewImage({
      urls: [that.data.imgPath + imgs], // 需要预览的图片http链接列表
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.opacity();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  // opacity: function(){
  //   var opacity = 1;
  //   // var inter = setInterval(function () {
  //   //   opacity = opacity - 0.1;
  //   //   if (opacity <= 0) {
  //   //     clearInterval(inter)
  //   //   }
  //   //   that.setData({
  //   //     opacity: opacity
  //   //   })
  //   // }, 10)
  // },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    var img = that.data.user_imgs;
    var cid = that.data.card.id;
    var limit = that.data.limit;
    var tatol = that.data.tatol
    if (img.length < tatol) {
      app.getUserInfo(function (personInfo) {
        var token = personInfo.token;
        wx.request({
          url: port.CardMyImg,//请求地址
          header: {//请求头
            "Content-Type": "applciation/json",
            "Authorization": "Bearer " + token
          },
          data: { 'cid': cid, limit: limit },
          method: "post",//get为默认方法/POST
          success: function (res) {
            if (res.data.status == 'success') {
              for (var i = 0; i < res.data.data.length; i++) {
                img.push(res.data.data[i])
              }
              that.setData({
                user_imgs: img,
                limit: that.data.limit + 1,
                tatol: res.data.tatol
              })
            }
          }
        })
      })
    }
  },
  wffx: function () {
    wx.showToast({
      title: '此名片涉嫌违规 无法分享',
      icon: 'none',
      mask: true,
      success: function () {
        return false
      }
    })
  },
  //去完善更多信息
  goPermessage: function(){
    var that=this;
    var indexMessage = that.data.indexMessage;
    wx.navigateTo({
      url: indexMessage + '/permessage/permessage?dataId=' + 2,
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    var path = "/pages/index/preview?cid=" + that.data.card.id + "&my=0";;
    return {
      title: 'V咖片',
      path: path,
      success: function (res) {
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
})